<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/10
 * Time: 21:35
 * 分享
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ShareRecord;
use think\Db;

class Share extends Api {
	
	protected $noNeedLogin = [];
	
	/**
	 * 分享记录
	 */
	public function index() {
		$userId = $this->auth->id;
		$model = new ShareRecord();
		$page = $this->request->post('page', 1, 'intval');
		$where['user_id'] = $userId;
		
		$count = $model->where($where)->group('goods_id')->group('goods_id')->count();
		$rows = $model->alias('r')
			->join('goods g', 'r.goods_id = g.id', 'left')
			->where(['r.user_id' => $userId])
			->page($page)
			->field('from_unixtime(r.create_time) as date, r.goods_id, g.image, g.name, g.price, g.number_sale')
			->group('goods_id')
			->select();
		
		if($rows) {
			foreach ($rows as &$row) {
				$row['number_view'] = $model->where(['user_id' => $userId, 'goods_id' => $row['goods_id']])->count();
				$row['commission'] = Db::name('commission')
					->where(['user_id' => $userId, 'goods_id' => $row['goods_id']])
					->sum('amount');
				$row['number_cart'] = Db::name('cart')
					->where(['recommend_user_id' => $userId, 'goods_id' => $row['goods_id']])
					->count();
				$wait = Db::name('orderGoods')->query('select sum(amount * number) as amount from fa_order_goods where recommend_user_id = '.$userId.' and goods_id = '.$row['goods_id'].' and status = 0');
				$row['wait_amount'] = $wait['amount'] ?? 0;
			}
		}
		
		$this->success('查询成功', [
			'list' => $rows,
			'total' => $count,
			'page' => $page
		]);
		
	}
	
	
	/**
	 * 访客进入
	 */
	public function enter() {
		$goodsId = $this->request->post('goods_id');
		$userId = $this->request->post('share_user_id');
		$viewUserId = $this->auth->id;
		$model = new ShareRecord();
		$res = $model->isUpdate(false)
			->save([
				'user_id' => $userId,
				'view_user_id' => $viewUserId,
				'goods_id' => $goodsId
			]);
		
		if($res) {
			$this->success('记录成功', ['id' => $model->getLastInsID()]);
		} else {
			$this->error('保存出错', $model->getError());
		}
	}
	
	/**
	 * 访客离开
	 */
	public function leave() {
		$id = $this->request->post('id');
		$model = new ShareRecord();
		$row = $model->find($id);
		!$row && $this->error('记录不存在');
		
		$res = $model->save([
			'duration' => time()-$row['create_time']
		], ['id' => $id]);
		if($res !== false) {
			$this->success('保存成功');
		} else {
			$this->error('保存出错', $model->getError());
		}
	}
}
